﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demos.DesignPatterns._21_观察者模式
{
    public class TOrderService: IOrderSubject
    {
        private List<IOrderObserver> _observers = new List<IOrderObserver>();
        private TOrderModel _order;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="orderId"></param>
        public TOrderService(string orderId)
        {
            _order = new TOrderModel
            {
                OrderId = orderId,
                Status = OrderStatus.Created,
                CustomerEmail = "customer@example.com",
                ProductIds = new List<string> { "P1001", "P1002" }
            };
        }

        /// <summary>
        /// 更新订单状态
        /// </summary>
        /// <param name="newStatus"></param>
        public void UpdateOrderStatus(OrderStatus newStatus)
        {
            _order.Status = newStatus;
            Console.WriteLine($"订单状态更新: {_order.OrderId} -> {newStatus}");
            Notify(_order);
            Thread.Sleep(700);
        }

        /// <summary>
        /// 通知所有观察者
        /// </summary>
        /// <param name="observer"></param>
        public void Attach(IOrderObserver observer)
        {
            Console.WriteLine("通知观察者...");
            _observers.Add(observer);
        }
        /// <summary>
        /// 移除观察者
        /// </summary>
        /// <param name="observer"></param>
        public void Detach(IOrderObserver observer)
        {
            Console.WriteLine("移除观察者...");
            _observers.Remove(observer);
        }
        /// <summary>
        /// 通知所有观察者
        /// </summary>
        /// <param name="order"></param>
        public void Notify(TOrderModel order)
        {
            Console.WriteLine("通知所有观察者...");
            foreach (var observer in _observers)
            {
                observer.Update(order);
            }
        }



    }
}
